<?php
    class product_dangsp_controller extends controllerBase
    {
        public function process()
        {
            database::isUser(true);
            if(isset($_POST['title']))
            {   
                $this->aParams['title'] = $_POST['title'];

                // Edit upload location here
                $destination_path = getcwd().DIRECTORY_SEPARATOR;
                $iImageCount = $_FILES['avatar']['name'];
                $aImages = array();
                for($i = 0; $i < count($_FILES['avatar']['name']) ; $i++)
                {
                    $file_name=$_FILES['avatar']['name'][$i];
                    if($file_name != '' && !empty($file_name))
                    {
                        $target_path = $destination_path . basename($file_name);

                        if(@move_uploaded_file($_FILES['avatar']['tmp_name'][$i], "upload/".$file_name)) {
                            $aImages[] = $file_name;
                        }
                        else
                        {
                            $this->aParams['error'] = 'Không thể upload file!';
                        }
                    }
                }
                // Neu upload file thanh cong thi them vao database
                if(count($aImages))
                {
                    // return id product
                    $iId = $this->addProduct($aImages);
                    if($iId)
                    {
                        $link = URL::getLink('product/id/'.$iId);
                        echo '<script type="text/javascript">window.top.window.uploadComplete("'.$link.'");</script>';
                    }
                    else
                    {
                        $this->aParams['error'] = 'ERROR!';
                    }
                }
            }
            $oDatabase = new database();
            $this->getManufacturer();
            $sQuery = 'SELECT * FROM location ';
            $aLocations = $oDatabase->getListObject($sQuery,true,true);
            $this->aParams['aLocations'] = $aLocations;

        }

        public function getManufacturer()
        {
            $oDatabase = new database();
            $squery = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/>
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX dc: <http://purl.org/dc/elements/1.1/>
            PREFIX bus: <'.URL::getLink('id/bussiness#').'>

            SELECT * 
            WHERE
            {
            ?uri rdf:type bus:manufacturer.
            ?uri bus:name ?name. 
            }';
            $aManufacturers = $oDatabase->loadQuery($squery);   
            $this->aParams['aManufacturers']=$aManufacturers['result']['rows'];
        }

        /**
        * add Product with param is image name
        * 
        * @param mixed $img
        */
        public function addProduct($aImages)
        {
            core::checkSession();
            $oDatabase = new database();
            $lastProduct = $oDatabase->getObject('SELECT * FROM settingid WHERE tablename = "product"');
            $product_id = core::getID($lastProduct->lastest_id,'product');
            $aData = array(
                'masp_id' => $product_id,
                'madm_id' => $_POST['dm_name'],
                'tensp' =>$_POST['tensp'],
                'dongia' =>$_POST['dongia'],
                'thoigian' =>"27-11-2013",
                'mota' =>$_POST['description'],
                'img' =>$aImages[0],
            );
            // Create resource rdf
            $result = $oDatabase->add('sanpham',$aData); 
            core::updateSettingID('product',((int)$lastProduct->lastest_id+1));
            $queryUser ='PREFIX foaf: <http://xmlns.com/foaf/0.1/>
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX dc: <http://purl.org/dc/elements/1.1/>
            PREFIX bus: <'.URL::getLink('id/bussiness#').'>

            SELECT * 
            WHERE
            {
            ?uri rdf:type foaf:Person.
            ?uri foaf:givenName ?name.
            OPTIONAL {?uri bus:followUser ?userfollow.}
            FILTER(?userfollow="'.$_SESSION['user_uri'].'" )
            }';
            $aUserFollow = $oDatabase->loadQuery($queryUser);   
            $listUserFollow=$aUserFollow['result']['rows'];
            if(count($listUserFollow))
            {
                $content = 'đã đăng một sản phẩm mới . ';
                foreach($listUserFollow as $user)
                {
                    $aData = array(
                        'user_send' => $_SESSION['username'],
                        'content' => $content ,
                        'user_to' =>$user['name'],
                        // Type 1: add product
                        'type' => 1,
                        'status' => 1,
                        'time' =>time(),
                        'avata' => $_SESSION['avatar'],
                        'product' =>$product_id,
                        'poup' => 1,
                    );
                    $result = $oDatabase->add('nofication',$aData); 
                }
            }
            // Add nofication when add product
            if($result)
            {
                $sType = 'product';
                $aNameSpace = array(
                    'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                    'bus' => URL::getLink('id/bussiness#'),
                );
                $uri = URL::getLink('product/id/'.$product_id);
                $data = array(
                    $uri => array(
                        "rdf:type" => array( 
                            array( "value" => URL::getLink("id/bussiness#product"), 
                                "type" => "uri" ) 
                        ) ,
                        "bus:name" => array(
                            array( "value" => $_POST['tensp'], 
                                "type" => "literal")
                        ),
                        "bus:price" => array(
                            array( "value" => $_POST['dongia'], 
                                "type" => "literal")
                        ),
                        "bus:description" => array(
                            array( "value" => $_POST['description'], 
                                "type" => "literal")
                        ),
                        "bus:defaultImage" => array(
                            array( "value" => URL::getLink('upload/'.$aImages[0]), 
                                "type" => "literal")
                        ),
                        "bus:hasCategory" => array(
                            array( "value" => $_POST['category_uri'], 
                                "type" => "uri")
                        ),
                        "bus:hasManufacturer" => array(
                            array( "value" => $_POST['dm_name'], 
                                "type" => "uri")
                        ),
                        "bus:ownUser" => array(
                            array( "value" => $_SESSION['user_uri'], 
                                "type" => "uri")
                        ),
                        "bus:location" => array(
                            array( "value" => $_POST['location_id'], 
                                "type" => "literal")
                        ),
                        "bus:publishDate" => array(
                            array( "value" => date('d'), 
                                "type" => "literal")
                        ),
                        "bus:publishTime" => array(
                            array( "value" => time(), 
                                "type" => "literal")
                        ),
                        "bus:publishMonth" => array(
                            array( "value" => date('m'), 
                                "type" => "literal")
                        ),
                        "bus:publishYear" => array(
                            array( "value" => date('Y'), 
                                "type" => "literal")
                        )
                    ) 
                );
                // Add image into array data
                $aImageTemps = array();
                foreach($aImages as $img)
                {
                    $aTemp = array( "value" => URL::getLink('upload/'.$img) ,"type" => "literal");
                    array_push($aImageTemps , $aTemp);
                }
                $data[$uri]['bus:image'] = $aImageTemps;
                // split sParentCategory into array Categories
                $str = chop($_POST['list_categories']);
                $sCategories = explode(';', $str);
                $aCategories = array();
                foreach($sCategories as $sCategory)
                {
                    $aTemp = array( "value" => $sCategory ,"type" => "uri");
                    array_push($aCategories , $aTemp);
                }
                $data[$uri]['bus:childCategoryOf'] = $aCategories;
                $oDatabase ->createResources($aNameSpace,$data,$product_id,$sType);
                return $product_id;
            }
            else
                return null;
        }
    }
?>